home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 18441 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: news.halcyon.com!usenet
  2. From: normanb@halcyon.com (Norm Bryar)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Standard struct layout in C++?
  5. Date: Sat, 20 Apr 1996 15:23:37 GMT
  6. Organization: Northwest Nexus Inc.
  7. Message-ID: <4lavga$5m6@news.halcyon.com>
  8. References: <4l739o$gt4$2@mhade.production.compuserve.com>
  9. NNTP-Posting-Host: blv-pm2-ip16.halcyon.com
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. anw <102044.3670@CompuServe.COM> wrote:
  13.  
  14. >Does C++ guarantee any data layout in classes (or structs)?  I
  15. >can't find any reference in Ellis and Stroustrup (the ARM).  The
  16. >problem I am trying to solve is reading and writing blocks of data
  17. >that represent classes or structures; e.g.:
  18.  
  19. >class foo;
  20.  
  21. >read(fd, buffer, sizeof(foo));
  22.  
  23. >Thanx,
  24.  
  25. >anw
  26.  
  27. I believe this is a risky habit, largely because it's a maintenance
  28. woe:
  29.  
  30. Unless you specifiy a structure packing (#pragma pack in MSVC), you
  31. don't know how your data may be aligned, 8-byte boundaries on a RISC
  32. chip, 2-byte on Win3.1, whatever,  so you have to be cautious.   
  33.  
  34. If the structs ever contain methods, the vtable could go ahead or
  35. behind the data, depending on the compiler (and maybe on the version
  36. of the compiler), and when such structs appear in multiple inheritence
  37. hierarchies, and esp multiple-virtual inheritence, there's no telling
  38. which compiler has put what vtable where.  
  39.  
  40. You may also chew up more disk-space than you wanted because your
  41. saving out padding and possibly vtables.
  42.  
  43. Some folks have taken to also comparing their structs with memcmp()
  44. instead of member-by-member.  Both the above problems come into play:
  45. esp packing because your globals pad with zero and your locals pad
  46. with random garbage.  
  47.  
  48. It's so much nicer to write a method for your data to persist (and
  49. compare) member-by-member and ask the base-class to do likewise.
  50.  
  51.                         --Norm 
  52.  
  53.  
  54.  
  55.  
  56.